package com.evan.petiymanta;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.multidex.MultiDex;

import com.bumptech.glide.Glide;
import com.hjq.language.MultiLanguages;

import org.lsposed.hiddenapibypass.HiddenApiBypass;

import java.util.Locale;

import lombok.Getter;
import rikka.sui.Sui;

public class Application extends android.app.Application {

    private static final boolean isSui;
    public static final String PREFS_NAME = "app_settings";
    public static final String KEY_LANGUAGE = "language";
    @Getter
    @SuppressLint("StaticFieldLeak")
    public static Context context;

    public static boolean isSui() {
        return isSui;
    }

    static {
        // 尝试初始化 Sui
        isSui = Sui.init(BuildConfig.APPLICATION_ID);
    }


    @Override
    protected void attachBaseContext(Context base) {
        // 多语言初始化
        super.attachBaseContext(MultiLanguages.attach(base));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            // 绕过 hidden API 限制
            HiddenApiBypass.addHiddenApiExemptions("L");
        }
        // MultiDex 初始化
        MultiDex.install(this);
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;

        // 初始化多语言
        MultiLanguages.init(this);

        // 初始化语言设置
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String savedLanguage = prefs.getString(KEY_LANGUAGE, "zh");
        setLocale(savedLanguage);
    }

    public static void setLocale(String languageCode) {
        SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
        editor.putString(KEY_LANGUAGE, languageCode);
        editor.apply();

        Locale locale = new Locale(languageCode);
        MultiLanguages.setAppLanguage(context, locale);
    }


    @Override
    public void onLowMemory() {
        super.onLowMemory();
        clearGlideMemory();
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        trimGlideMemory(level);
    }

    /**
     * 清理 Glide 内存缓存
     */
    private void clearGlideMemory() {
        Glide.get(this).onLowMemory();
    }

    /**
     * 根据内存等级调整 Glide 缓存
     */
    private void trimGlideMemory(int level) {
        Glide.get(this).onTrimMemory(level);
    }
}
